<?php
class Site_SiteController extends Promotor_Controller_Action_Scaffold {
	
	public $skin = array(
		// forsuje domyslny template i style na admin
		'template' => 'admin',
		'style' => 'default',
		// layout
		'layout' => 'admin_site',
		// rozszerzam konfiguracje
		'config' => array(
			'filename' => 'backend_config.ini'
		),

		// specjalizuje template dla akcji
		'display' => array(
			'personalized' => true,
			'layout' => 'site_display_one'
		)
	);

	public $ajaxable = array(
		'display' => array('html','html#main'),
		'list' => array('jsTree'),
	);
	
	public $acl = array(
		'list' => 'list',
		'export' => 'list',
		'add' => 'create',
		'addfromodt' => 'create',
		'edit' => 'update',
		'move' => 'update',
		'display' => 'show',
		'delete' => 'delete'
	);

	/**
	 * @see Promotor_Controller_Action_Scaffold specialization
	 */
	protected $_modelClass = 'Site_Model_Site';
	protected $_formAddClass = 'Site_Form_SiteAdd';
	protected $_formEditClass = 'Site_Form_SiteEdit';
	protected $_formRemoveClass = 'Site_Form_SiteRemove';
	
	protected $_pagination = false;
	
	//	protected $_addPostObservableName;
	protected $_editPostObservableName = 'site_edit_post';
	protected $_deletePostObservableName = 'site_delete_post';
	
	public function init() {
		/* @var Zend_Controller_Action_Helper_AjaxContext */
		$ajaxContext = $this->_helper->getHelper('AjaxContext');
		if (!$ajaxContext->hasContext('jsTree')) {
			$ajaxContext->addContext('jsTree', array(
				'suffix' => 'jstree'
			));
		}
		if (!$ajaxContext->hasContext('html#main')) {
			$ajaxContext->addContext('html#main', array(
				'suffix' => 'ajax'
			));
		}
        $ajaxContext->initContext();
	}
	
	public function indexAction() {
		
	}

	/**
	 * @return void
	 */
	public function displayAction() {
		/* @var $model Site_Model_Site */
		$model = new Site_Model_Site();
		$table = $model->getDbTable();

		$locale = $this->_getParam('locale');
		$identification = $this->_getParam('alias', $this->_getParam('id'));
		
		if (!$identification)
		{
			$this->_helper->viewRenderer->render('display.404');
		}
		
		/* @var $row KontorX_Db_Table_Tree_Row_Abstract */
		$row = $model->findByIdentificationAndLocaleCache($identification, $locale, false);

		if ($model->getStatus() === Site_Model_Site::FAILURE
				|| !$row instanceof Zend_Db_Table_Row_Abstract)
		{
			$this->_helper->viewRenderer->render('display.404');
			return;
		}
		
		$this->view->row = $row->toArray();

		if (strlen($row->redirect) > 0) {
			$this->_helper->redirector
				->setCode(301)
				->goToUrlAndExit($row->redirect);
			return;
		}

		$templateData = $model->getTemplateDataCache($row);

		switch (@$templateData['columns']) {
			default:
			case 'ONE': 	 $layout = 'site_display_one'; break;
			case 'TWO_LEFT': $layout = 'site_display_two_left'; break;
			case 'TWO_RIGHT':$layout = 'site_display_two_right'; break;
			case 'THREE': 	 $layout = 'site_display_three'; break;
		}

		/* @var $template KontorX_Template_Controller_Action_Helper_Template */
		$template = $this->_helper->getHelper('template');
		$template->setLayoutName($layout);

		if (strlen(@$templateData['template']) > 0) {
			$template->setTemplateName($templateData['template']);
		}
		if (strlen(@$templateData['style']) > 0) {
			$template->setStyleName($templateData['style']);
		}
		
		if ($this->_hasParam('news')) {
			$template->lockLayoutName(true);

			$params = $this->_getAllParams();
			$params['id'] = $params['news'];
			$params['fromSite'] = array(
				'name' => $row['name'],
				'alias' => $row['alias']);

			unset($params['news']); 

			$params['responseSegment'] = 'news';
			
			// ActionStack.. wyrederowany widok dodaje do body 
			$this->_helper->actionStack('display','news','news', $params);
			// a _forward pomija renderowanie widoku
			// $this->_forward('display','news','news', $params);

		} else
		if ($this->_hasParam('album')) {
			$template->lockLayoutName(true);

			$params = $this->_getAllParams();
			$params['id'] = $params['album'];
			$params['fromSite'] = array(
				'name' => $row['name'],
				'alias' => $row['alias']);

			unset($params['album']); 

			$params['responseSegment'] = 'album';

			// ActionStack.. wyrederowany widok dodaje do body 
			$this->_helper->actionStack('display','album','gallery', $params);
			// a _forward pomija renderowanie widoku
			// $this->_forward('display','news','news', $params);

		} else
		if ($row->__get('display_news')) {
			$this->view->attachments = $model->findAttachments($row);
		}
	}
	
	/**
	 * Manipuluje położeniem zagnieżdzeń
	 * @return void
	 */
	public function moveAction() {
		$model = new Site_Model_Site();

		$form = new Site_Form_SiteMove();

		$rq = $this->getRequest();
		if (!$rq->isPost()) {
			$this->view->form = $form;
			return;
		}

		if (!$form->isValid($rq->getPost())) {
			$this->view->form = $form;
			return;
		}

		// magic
        $model->move($this->_getParam('id'),
        			 $form->getSubForm('movetab')->getValue('movePk'));

		$status = $model->getStatus();
		$messages = $model->getMessages();

		/* @var $flashMessenger Zend_Controller_Action_Helper_FlashMessenger */
		$flashMessenger = $this->_helper->getHelper('flashMessenger');
		$flashMessenger->addMessage($status);
		array_map(array($flashMessenger, 'addMessage'), $messages);

		if ($status == Site_Model_Site::SUCCESS) {
			$this->_helper->redirector->goToAndExit('list');
		} else {
			$this->view->form = $form;
		}
    }
    
	/**
	 * Kopiowanie zaznaczonych stron do innego locale
	 * @return void
	 */
	public function copyAction()
	{
		$rq = $this->getRequest();
		$form = new Site_Form_SiteCopy();

		if (!$rq->isPost()) {
			$this->view->form = $form;
			return;
		}

		if (!$form->isValid($rq->getPost())) {
			$this->view->form = $form;
			return;
		}

		$locale = $form->getSubForm('copytab')
						->getElement('locale')
						->getValue();

		$jsonData = $rq->getParam('jsonData');
		$data = Zend_Json::decode($jsonData);
		
		$model = new Site_Model_Site();
        $model->copy($locale, $data);

		$status = $model->getStatus();
		$messages = $model->getMessages();

		/* @var $flashMessenger Zend_Controller_Action_Helper_FlashMessenger */
		$flashMessenger = $this->_helper->getHelper('flashMessenger');
		$flashMessenger->addMessage($status);
		array_map(array($flashMessenger, 'addMessage'), $messages);

		if ($status == Site_Model_Site::SUCCESS) {
			$this->_helper->redirector->goToAndExit('list');
		} else {
			$this->view->form = $form;
		}
    }
	
	/**
	 * Tworzy stronę o zawartość uploadowanego pliku OpenOffice.org
	 * @return void
	 */
	public function addfromodtAction() {		
		$model = new Site_Model_Site();
		$dbTable = $model->getDbTable();

		$form = new Site_Form_UploadOdt();
		
		$rq = $this->getRequest();
		if (!$rq->isPost()) {
			$this->view->form = $form;
			return;
		}
		
		if (!$form->isValid($rq->getPost())) {
			$this->view->form = $form;
			return;
		}

		$transfer = $form->getSubForm('filetab')
						 ->getElement('file')
						 ->getTransferAdapter();

		$primaryKey = $model->addFromOdt($transfer);

		$status = $model->getStatus();
		$messages = $model->getMessages();

		$flashMessenger = $this->_helper->getHelper('flashMessenger');
		$flashMessenger->addMessage($status);
		foreach ($messages as $message) {
			$flashMessenger->addMessage($message);
		}

		if ($status == Site_Model_Site::SUCCESS) {
			$this->_helper->redirector->goToAndExit('edit',null,null,array('id'=>$primaryKey));
		} else {
			$this->view->form = $form;
		}
	}

	/**
	 * Eksport bazy do CVS
	 * TODO Zły eksport
	 * @return void
	 */
	public function exportAction() {
		// wylaczenie renderowania widoku
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $model = new Site_Model_Site();
        $path = $model->export();
        
        $status = $model->getStatus();
		if ($status == Site_Model_Site::SUCCESS) {
			$response = $this->getResponse();
			$response->setHeader('Content-type','application/csv ');
			$response->setHeader('Content-Disposition','attachment; filename="site-expostt.csv"');
			$response->setBody(@file_get_contents($path));
		} else {
			$flashMessenger = $this->_helper->getHelper('flashMessenger');
			$flashMessenger->addMessage($status);

			$messages = $model->getMessages();
			foreach ($messages as $message) {
				$flashMessenger->addMessage($message);
			}

			$this->_redirect('list');
		}
	}
}